package com.yanqu.road.server.cmd.cricket;

import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cricket.CricketProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.CmdApi;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.cricket.CricketMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.sync.message.SyncResponse;

import java.util.concurrent.CompletableFuture;

@CmdApi(reqMsg = CricketProto.CricketWatchPlayerSimpleReqMsg.class, respMsg = CricketProto.CricketWatchPlayerSimpleRespMsg.class)
@Cmd(code = Protocol.S_CRICKET_WATCH_OTHER, desc = "查看他人蛐蛐")
public class CricketWatchPlayerCmd extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        CricketProto.CricketWatchPlayerSimpleReqMsg reqMsg = CricketProto.CricketWatchPlayerSimpleReqMsg.parseFrom(packet.getBytes());

        if (reqMsg.getUserId() == packet.getPlayerId()) {
            ret = GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            return;
        }
        CricketProto.CricketWatchPlayerSimpleRespMsg.Builder clientMsg;
        if (reqMsg.getServerId() == GameServer.getInstance().getServerId()) {
            clientMsg = CricketMgr.watch(reqMsg.getUserId());
            player.sendPacket(Protocol.U_CRICKET_WATCH_OTHER, clientMsg);
        } else {
            clientMsg = CricketProto.CricketWatchPlayerSimpleRespMsg.newBuilder();
            CompletableFuture<SyncResponse> responseFuture = GamePlayerMgr.sendToGameServer(reqMsg.getServerId(), GameProtocol.S_CRICKET_SERVICE_WATCH_OTHER_USER, player.getUserId(), reqMsg.toBuilder(), clientMsg);
            responseFuture.thenAccept(syncResponse -> {
                if (syncResponse.getErrorCode() == 0) {
                    player.sendPacket(Protocol.U_CRICKET_WATCH_OTHER, clientMsg);
                }
            });
        }
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            player.sendPacket(Protocol.U_CRICKET_WATCH_OTHER, CricketProto.CricketWatchPlayerSimpleRespMsg.newBuilder().setRet(ret));
        }
    }
}
